package cn.hfatec.shms.web.members.ykManage.action;

import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.base.ShmsBaseAction;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.exception.NotAuthException;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.system.user.model.UserParams;
import cn.hfatec.shms.system.user.service.UserService;
import cn.hfatec.shms.web.members.cardType.dao.CardTypeDao;
import cn.hfatec.shms.web.members.cardType.model.CardType;
import cn.hfatec.shms.web.members.ykManage.model.YkManage;
import cn.hfatec.shms.web.members.ykManage.model.YkManageParams;
import cn.hfatec.shms.web.members.ykManage.model.YkManageView;
import cn.hfatec.shms.web.members.ykManage.service.YkManageService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;


/**
 * @author hfatec codegen
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Controller
@RequestMapping("/members/ykManage")
public class YkManageAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "YkManageService")
    private YkManageService ykManageService;

    //服务层
    @Resource(name = "UserService")
    private UserService userService;
    //注入Dao层
    @Resource(name = "CardTypeDao")
    private CardTypeDao cardTypeDao;


    /**
     * 查询列表
     */
    @RequestMapping("/list")
    public String list(YkManageParams ykManageParams, Page page, Model model) {

        Table table = ykManageService.queryYkManageTable(ykManageParams, page);
        model.addAttribute("ykManagesTable", table);
        model.addAttribute("usersList", userService.queryUserList(new UserParams()));
        model.addAttribute("ykManageParams", ykManageParams);
        model.addAttribute("vipTypeList", CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE));
        model.addAttribute("channelTypeList", CodeInfoCache.getCodeInfo(CodeType.CHANNEL_TYPE));
        return "/members/ykManage/list";
    }

    /**
     * 异步查询列表
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(YkManageParams ykManageParams, Page page, Model model) {
        try {
            list(ykManageParams, page, model);
            model.addAttribute("vipTypeList", CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE));
            model.addAttribute("channelTypeList", CodeInfoCache.getCodeInfo(CodeType.CHANNEL_TYPE));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/members/ykManage/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 异步查询列表
     */
    @RequestMapping("/ajaxykList")
    @ResponseBody
    public String ajaxykList(YkManageParams ykManageParams, Page page, Model model) {
        try {
            list(ykManageParams, page, model);
            model.addAttribute("vipTypeList", CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE));
            model.addAttribute("channelTypeList", CodeInfoCache.getCodeInfo(CodeType.CHANNEL_TYPE));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/members/ykLog/yktable", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到新增页
     */
    @RequestMapping("/goAdd")
    @ResponseBody
    public String goAdd(Model model) {
        try {
            YkManage ykManage = new YkManage();
            model.addAttribute("ykManage", ykManage);
            model.addAttribute("channelTypeList", CodeInfoCache.getCodeInfo(CodeType.CHANNEL_TYPE));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/members/ykManage/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goEdit")
    @ResponseBody
    public String goEdit(Integer id, Model model) {

        try {
            YkManageView ykManage = ykManageService.getYkManage(id);
            model.addAttribute("ykManage", ykManage);
            model.addAttribute("channelTypeList", CodeInfoCache.getCodeInfo(CodeType.CHANNEL_TYPE));
            model.addAttribute("usersList", userService.queryUserList(new UserParams()));

            String healthCh = ykManage.getHealthCh();
            if (StringUtils.isNotBlank(healthCh)) {
                if (healthCh.contains(",")) {
                    String[] array = healthCh.split(",");
                    String userName = "";
                    for (String str : array) {
                        User user = userService.getUserByLoginName(str);
                        userName += user.getUserName() + ",";
                    }
                    model.addAttribute("userName", userName);
                }
            }

            String healthYj = ykManage.getHealthYj();
            if (StringUtils.isNotBlank(healthYj)) {
                if (healthYj.contains(",")) {
                    String[] array = healthYj.split(",");
                    String userNameYj = "";
                    for (String str : array) {
                        User user = userService.getUserByLoginName(str);
                        userNameYj += user.getUserName() + ",";
                    }
                    model.addAttribute("userNameYj", userNameYj);
                }
            }
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/members/ykManage/form", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 根据IDs删除数据
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteYkManage(String ids) {
        try {
            List<String> idList = new ArrayList<String>();
            if (ids.length() > 0) {
                idList = Arrays.asList(ids.split(","));
            }
            ykManageService.deleteYkManageBatch(idList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据" + ids + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 保存数据
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveYkManage(@Valid YkManage ykManage, BindingResult result, HttpServletRequest request) throws NotAuthException {
        try {
            User user = (User) request.getSession().getAttribute(SysContant.LOGIN_USER_SESSION);
            if (user == null) {
                throw new NotAuthException("用户未授权");
            }
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            ykManageService.saveYkManage(ykManage, user);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据YkManage保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }


    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goFind")
    @ResponseBody
    public String goFind(Integer vipId, String cardId) {
        try {
            YkManageView ykManage = ykManageService.getYkManageFind(cardId);
            if (ykManage != null) {
                ykManage.setStartDate(ykManage.getEndendDate());
                CardType cardType = cardTypeDao.getCardTypeById(vipId);
                Date dt = ykManage.getStartDate();
                Calendar rightNow = Calendar.getInstance();
                rightNow.setTime(dt);
                rightNow.add(Calendar.MONTH, cardType.getCycle());
                Date enddate = rightNow.getTime();
                ykManage.setEndDate(enddate);
                return new JsonResponse(JsonResponse.RETURN_SUCCESS, "", ykManage).toString();
            } else {
                return new JsonResponse(JsonResponse.RETURN_SUCCESS, "", new YkManageView()).toString();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goBlur")
    @ResponseBody
    public String goBlur(Date startDate, Integer vipId) {
        try {
            YkManageView ykManage = new YkManageView();
            CardType cardType = cardTypeDao.getCardTypeById(vipId);
            Date dt = startDate;
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(dt);
            rightNow.add(Calendar.MONTH, cardType.getCycle());
            Date enddate = rightNow.getTime();
            ykManage.setEndDate(enddate);
            if (startDate != null) {
                return new JsonResponse(JsonResponse.RETURN_SUCCESS, "", ykManage).toString();
            } else {
                return new JsonResponse(JsonResponse.RETURN_SUCCESS, "", new YkManageView()).toString();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到新增页
     */
    @RequestMapping("/deletes")
    @ResponseBody
    public String Deletes(String ids, Model model) {
        try {
            YkManage ykManage = new YkManage();
            model.addAttribute("ykManage", ykManage);
            model.addAttribute("ids", ids);
            model.addAttribute("channelTypeList", CodeInfoCache.getCodeInfo(CodeType.CHANNEL_TYPE));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/members/ykManage/forms", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 批量修改分管人员数据
     */
    @RequestMapping("/saveUserNameFg")
    @ResponseBody
    public String saveUserNameFg(String ids, String healthFg) {
        try {
            List<String> idList = new ArrayList<String>();
            if (ids.length() > 0) {
                idList = Arrays.asList(ids.split(","));
            }
            ykManageService.updateYkManageBatch(idList, healthFg);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据" + ids + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }


}
